package cn.kinoko.service.ai.ocr.impl;

import cn.kinoko.common.base.model.BaseServiceImpl;
import cn.kinoko.common.code.ErrorCodeEnum;
import cn.kinoko.common.utils.ExceptionUtil;
import cn.kinoko.common.utils.LinearRegression;
import cn.kinoko.mapper.ai.ocr.OcrLrCalibrateMapper;
import cn.kinoko.model.ai.ocr.dto.OcrLrCalibrateDto;
import cn.kinoko.model.ai.ocr.entity.OcrLr;
import cn.kinoko.model.ai.ocr.entity.OcrLrCalibrate;
import cn.kinoko.service.ai.ocr.OcrLrCalibrateService;
import cn.kinoko.service.ai.ocr.OcrLrService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liujunkai
 * @date 2024/8/14 16:01
 */
@Service
public class OcrLrCalibrateServiceImpl extends BaseServiceImpl<OcrLrCalibrateMapper, OcrLrCalibrate> implements OcrLrCalibrateService {

    @Resource
    private OcrLrService ocrLrService;

    /**
     * 矫正
     * @param ocrType ocr类型
     */
    @Override
    public void calibrate(String ocrType) {
        // 查询ocr线性回归系数
        OcrLr ocrLr = ocrLrService.getById(ocrType);
        ExceptionUtil.isNull(ocrLr, ErrorCodeEnum.SYSTEM_ERROR_B0409);

        // 查询矫正数据
        List<OcrLrCalibrateDto> data = getBaseMapper().queryCalibrateData(ocrType);
        if (data.isEmpty()) return;

        // 准备数据
        double[] xTargetData = new double[data.size()];
        double[] xPrimitiveData = new double[data.size()];

        double[] yTargetData = new double[data.size()];
        double[] yPrimitiveData = new double[data.size()];

        for (int i = 0; i < data.size(); i++) {
            OcrLrCalibrateDto dto = data.get(i);
            xTargetData[i] = dto.getTargetX();
            xPrimitiveData[i] = dto.getPrimitiveX();

            yTargetData[i] = dto.getTargetY();
            yPrimitiveData[i] = dto.getPrimitiveY();
        }

        // 计算线性回归系数
        LinearRegression xRegression = new LinearRegression(xPrimitiveData, xTargetData);
        LinearRegression yRegression = new LinearRegression(yPrimitiveData, yTargetData);

        xRegression.fit();
        yRegression.fit();

        // 更新系数
        ocrLr.setXSlope(String.valueOf(xRegression.getSlope()));
        ocrLr.setXIntercept(String.valueOf(xRegression.getIntercept()));
        ocrLr.setYSlope(String.valueOf(yRegression.getSlope()));
        ocrLr.setYIntercept(String.valueOf(yRegression.getIntercept()));
        ocrLrService.updateById(ocrLr);
    }

    /**
     * 清理未矫正的数据
     *
     * @param ocrType ocr类型
     */
    @Override
    public void clearNotCalibrateData(String ocrType) {
        getBaseMapper().clearNotCalibrateData(ocrType);
    }
}